package com.snow.useviewdemo.function.wallpaper;

import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.LruCache;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.FutureTarget;
import com.snow.useviewdemo.R;
import com.snow.useviewdemo.util.HandlerHelper;
import com.snow.useviewdemo.util.ThreadCacheTools;

import java.util.Map;
import java.util.concurrent.ExecutionException;

public class SZWallpaperView extends SurfaceView implements SurfaceHolder.Callback {

    private final static String CACHE_WALLPAPER = "cache_wallpaper";

    private Context mContext;
    private Paint mPaint;
    private LruCache<String, Bitmap> mMemoryCache;
    // 系统默认壁纸-第三方设置壁纸
    private Bitmap mDefaultBitmap;
    private SZWallpaperService.WallpaperEngine mEngine;


    public SZWallpaperView(SZWallpaperService.WallpaperEngine engine, Context context) {
        super(context);
        this.mContext = context;
        this.mEngine = engine;
        this.initCacheConfig();
        this.initPaintConfig();
    }

    private void initPaintConfig() {
        this.mPaint = new Paint();
        this.mPaint.setAntiAlias(true);
        this.mPaint.setStyle(Paint.Style.STROKE);
        this.mPaint.setStrokeWidth(5);
    }

    private void initCacheConfig() {
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        this.mMemoryCache = new LruCache<String, Bitmap>(maxMemory / 8) {

            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight();
            }
        };
    }

    public void initView() {
        loadDefaultWallpaperBitmap();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        holder.removeCallback(this);
        drawSurfaceView(holder);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
//        drawSurfaceView(holder);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        releaseBitmap();
    }

    /**
     * 绘制图片
     * @param holder
     */
    private void drawSurfaceView(SurfaceHolder holder) {
        Canvas localCanvas = holder.lockCanvas();
        ThreadCacheTools.newThread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = getBitmap();
                if (localCanvas != null) {
                    // 方案一：图片放大
//                    Matrix matrix = new Matrix();
//                    matrix.postScale(localCanvas.getHeight() * 1f  / bitmap.getHeight(), localCanvas.getHeight() *1f  / bitmap.getHeight(), bitmap.getWidth() / 2, bitmap.getHeight() / 2);
//                    matrix.postTranslate((localCanvas.getWidth() - bitmap.getWidth()) / 2, (localCanvas.getHeight() - bitmap.getHeight()) / 2);
//                    localCanvas.drawBitmap(bitmap, matrix, mPaint);

                    // 方案二：背景层+文字层
                    // 绘制背景
                    Rect rect = new Rect();
                    rect.left = rect.top = 0;
                    rect.bottom = localCanvas.getHeight();
                    rect.right = localCanvas.getWidth();
                    localCanvas.drawBitmap(bitmap, null, rect, mPaint);

                    // 绘制文字层
                    if (mTextBitmap != null) {
                        float rate = bitmap.getWidth() * 1f / bitmap.getHeight();
                        int diff = Math.abs((localCanvas.getHeight() - mTextBitmap.getHeight()) / 6);
                        Rect rectText = new Rect();
                        rectText.left = 0;
                        rectText.top = diff;
                        rectText.bottom = (int) (localCanvas.getWidth() / rate) + diff;
                        rectText.right = localCanvas.getWidth();
                        localCanvas.drawBitmap(mTextBitmap, null, rectText, mPaint);
                    }
                }
                HandlerHelper.post(()->{
                    try {
                        holder.unlockCanvasAndPost(localCanvas);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }

    private Bitmap mTextBitmap = null;
    private Bitmap getBitmap() {
        if (mContext == null) {
            return this.mDefaultBitmap;
        }
        Bitmap bitmap = null;
        // 用于处理预览图片
        if (mEngine.isPreview()) {
            FutureTarget<Bitmap> futureBitmap = Glide.with(mContext).asBitmap().fitCenter()
                    .load(R.mipmap.bg_wallpaper)
                    .submit();
            try {
                bitmap = futureBitmap.get();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            FutureTarget<Bitmap> futureTxtBitmap = Glide.with(mContext).asBitmap().fitCenter()
                    .load(R.mipmap.bg_txt_wallpaper)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .submit();
            try {
                mTextBitmap = futureTxtBitmap.get();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (bitmap != null) {
            return bitmap;
        }
        // 实际设置背景图片
        return this.mDefaultBitmap;
    }

    /**
     * 加载默认壁纸图片
     */
    public void loadDefaultWallpaperBitmap() {
        if (mMemoryCache == null || mContext == null) {
            return;
        }

        try {
            Bitmap bitmap = this.mMemoryCache.get(CACHE_WALLPAPER);
            if (bitmap == null) {
                Drawable drawable = WallpaperManager.getInstance(mContext).getDrawable();
                if (drawable == null) {
                    return;
                }
                bitmap = ((BitmapDrawable) drawable).getBitmap();
                if (bitmap != null) {
                    this.mMemoryCache.put(CACHE_WALLPAPER, bitmap);
                }
            }
            if (bitmap != null) {
                this.mDefaultBitmap = bitmap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放动态壁纸
     */
    public void releaseBitmap() {
        try {
            if (mMemoryCache != null && mMemoryCache.size() > 0) {
                Map<String, Bitmap> stringBitmapMap = mMemoryCache.snapshot();
                mMemoryCache.evictAll();
                if (stringBitmapMap != null && stringBitmapMap.size() > 0) {
                    for (Map.Entry<String, Bitmap> entry : stringBitmapMap.entrySet()) {
                        if (entry != null && entry.getValue() != null && !entry.getValue().isRecycled()) {
                            entry.getValue().recycle();
                        }
                    }
                    stringBitmapMap.clear();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
